console.log('popup.js');
const changeColor = document.getElementById('changeColor');
// const btn1 = document.getElementById('btn1');
const myul = document.getElementById('myul');

chrome.storage.local.get('color', (data) => {
  changeColor.style.backgroundColor = data.color;
  changeColor.setAttribute('value', '变色');
  changeColor.setAttribute('data-color', data.color);
})

changeColor.onclick = (e) => {
  console.log(e);
  console.log(e.currentTarget.dataset.color);
  let color = e.currentTarget.dataset.color;
  // 获取具有指定属性的所有标签页，如果没有指定任何属性的话则获取所有标签页。
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    console.log(tabs[0]);
    chrome.tabs.executeScript(
      tabs[0].id,
      { code: `document.body.style.backgroundColor = "${color}"` },
      () => { console.log('脚本执行完成') }
    )
  })
}

// btn1.onclick = (e) => {
//   console.log(e);
//   chrome.tabs.create({ url: 'https://www.cnblogs.com/champagne/p/?page=2' }, (tab) => {
//     console.log(tab);
//   })
// }

chrome.storage.local.get('pages', (result) => {
  console.log(result.pages);
  let pages = result.pages;
  pages.forEach((element, index) => {
    console.log(element)
    let alink = document.createElement('a');
    let title = document.createTextNode(index + 1 + '. ' + element.title);
    alink.appendChild(title);
    alink.setAttribute('href', '#');
    alink.setAttribute('data-url', element.url);
    alink.addEventListener('click', function (e) {
      console.log(e.currentTarget.dataset.url);
      chrome.tabs.create({ url: e.currentTarget.dataset.url }, (tab) => {
        console.log(tab);
      })
    })
    let li = document.createElement('li');
    li.appendChild(alink);
    myul.appendChild(li);
  });
})

document.getElementById('clearBtn').addEventListener('click', function () {
  console.log('clearBtn');
  chrome.storage.local.remove('pages', () => {
    console.log('pages remove');
    chrome.storage.local.set({ 'pages': [] }, () => { })
  })
  let element = document.getElementById('myul');
  while (element.firstChild) {
    element.removeChild(element.firstChild);
  }

});

// document.getElementsByClassName('nextlink')[0].click();
document.getElementById('autoPlay').addEventListener('click', function () {
  console.log('autoPlay 触发');
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    console.log(tabs[0]);
    chrome.tabs.executeScript(
      tabs[0].id,
      { file: "/autoplay.js", allFrames: true },
      () => { console.log('脚本执行完成');
        document.getElementById('autoPlay').setAttribute('value', '已经点击');
      }
    )
  })
});